
// Control ServiceDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Control Service.h"
#include "Control ServiceDlg.h"


#include "winsvc.h"
#include <tchar.h>
#include <stdio.h>


#define UD_WEAVE_REQUEST 128
#define UD_UNWEAVE_REQUEST 129


#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CControlServiceDlg dialog

BEGIN_DHTML_EVENT_MAP(CControlServiceDlg)
	DHTML_EVENT_ONCLICK(_T("ButtonOK"), OnButtonOK)
	DHTML_EVENT_ONCLICK(_T("ButtonCancel"), OnButtonCancel)
END_DHTML_EVENT_MAP()



CControlServiceDlg::CControlServiceDlg(CWnd* pParent /*=NULL*/)
	: CDHtmlDialog(CControlServiceDlg::IDD, CControlServiceDlg::IDH, pParent)
  , m_csBinaryFile(_T(""))
  , m_csServiceName(_T("SampleService"))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CControlServiceDlg::DoDataExchange(CDataExchange* pDX)
{
  CDHtmlDialog::DoDataExchange(pDX);
  DDX_Text(pDX, IDC_EDIT_BINARY, m_csBinaryFile);
  DDX_Text(pDX, IDC_EDIT_SERVICENAME, m_csServiceName);
}

BEGIN_MESSAGE_MAP(CControlServiceDlg, CDHtmlDialog)
	ON_WM_SYSCOMMAND()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_install, &CControlServiceDlg::OnBnClickedinstall)
	ON_BN_CLICKED(IDC_uninstall, &CControlServiceDlg::OnBnClickeduninstall)
	ON_BN_CLICKED(IDC_start, &CControlServiceDlg::OnBnClickedstart)
	ON_BN_CLICKED(IDC_stop, &CControlServiceDlg::OnBnClickedstop)
	ON_BN_CLICKED(IDC_weave, &CControlServiceDlg::OnBnClickedweave)
	ON_BN_CLICKED(IDC_unweave, &CControlServiceDlg::OnBnClickedunweave)
END_MESSAGE_MAP()


// CControlServiceDlg message handlers

BOOL CControlServiceDlg::OnInitDialog()
{
	CDHtmlDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	ShowWindow(SW_MINIMIZE);

	// TODO: Add extra initialization here

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CControlServiceDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDHtmlDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CControlServiceDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDHtmlDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CControlServiceDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

HRESULT CControlServiceDlg::OnButtonOK(IHTMLElement* /*pElement*/)
{
	OnOK();
	return S_OK;
}

HRESULT CControlServiceDlg::OnButtonCancel(IHTMLElement* /*pElement*/)
{
	OnCancel();
	return S_OK;
}

void CControlServiceDlg::OnBnClickedinstall()
{
	// TODO: Add your control notification handler code here
 UpdateData();

 LPCTSTR lpszBinaryPathName = m_csBinaryFile;
        //"C:\\MasterProject\\stage1\\MYOCC\\Debug\\myapplication_stage1.exe"; 
        //"C:\\MasterProject\\stage1\\MYOCC\\Debug\\sampleservice.exe"; 
        
        //"\"C:\\Documents and Settings\\jn\\Dokumenter\\Visual Studio 2008\\Projects\\sampleservice\\Debug\\sampleservice.exe\"";

	LPCTSTR lpszDisplayName = m_csServiceName;

	 CString message;

	SC_HANDLE  schSCManager;
	SC_HANDLE  schService;


	schSCManager = OpenSCManager( 
    NULL,                    // local machine 
    NULL,                    // ServicesActive database 
    SC_MANAGER_ALL_ACCESS);  // full access rights 
 
   if (schSCManager == NULL) 
   {   //MyErrorExit("OpenSCManager");
	   message="Could not access the services control manager";
	   
	   MessageBox(message," Error",MB_OK);


	   return;

   }





 
    schService = CreateService( 
        schSCManager,              // SCManager database 
        m_csServiceName,              // name of service 
        lpszDisplayName,           // service name to display 
        SERVICE_ALL_ACCESS,        // desired access 
        SERVICE_WIN32_OWN_PROCESS, // service type 
        SERVICE_AUTO_START,      // start type 
        SERVICE_ERROR_NORMAL,      // error control type 
        lpszBinaryPathName,        // service's binary 
        NULL,                      // no load ordering group 
        NULL,                      // no tag identifier 
        NULL,                      // no dependencies 
        NULL,                      // LocalSystem account 
        NULL);                     // no password 
 
    if (schService == NULL) 
	{    //MyErrorExit("CreateService"); 
	  message="Could not install the service ";
	  message+=lpszDisplayName;
	   MessageBox(message," Error",MB_OK);

	    CloseServiceHandle(schSCManager); 

	   return;

	}
    else 
	{ // printf("CreateService SUCCESS.\n"); 
		message="The service has been installed successfully ";
		message+=lpszDisplayName;
       MessageBox(message,"",MB_OK);
	}

 
    CloseServiceHandle(schService); 
	CloseServiceHandle(schSCManager); 















}

void CControlServiceDlg::OnBnClickeduninstall()
{
 UpdateData();

LPCTSTR lpszDisplayName =m_csServiceName;

	 CString message;

	SC_HANDLE  schSCManager;
	SC_HANDLE  schService;
	

	schSCManager = OpenSCManager( 
    NULL,                    // local machine 
    NULL,                    // ServicesActive database 
    SC_MANAGER_ALL_ACCESS);  // full access rights 
 
   if (schSCManager == NULL) 
   {   //MyErrorExit("OpenSCManager");
	   message="Could not access the services control manager";
	   
	   MessageBox(message," Error",MB_OK);
	   return;

   }

	schService = OpenService( 
        schSCManager,       // SCManager database 
        m_csServiceName,       // name of service 
        DELETE);            // only need DELETE access 
 
    if (schService == NULL) 
  {   //MyErrorExit("OpenSCManager");
	   message="Could not access the service for deleting ";
	   
	   MessageBox(message," Error",MB_OK);

	    CloseServiceHandle(schSCManager); 

	   return;

   }
 
    if (! DeleteService(schService) ) 
	{ // printf("CreateService SUCCESS.\n"); 
		message="Could not Delete The service ";
		message+=lpszDisplayName;
       MessageBox(message,"",MB_OK);
	}

    else 
	{ // printf("CreateService SUCCESS.\n"); 
		message="The following service has been deleted: ";
		message+=lpszDisplayName;
       MessageBox(message,"",MB_OK);
	}
 
    CloseServiceHandle(schService); 
	CloseServiceHandle(schSCManager);
}

void CControlServiceDlg::OnBnClickedstart()
{
  UpdateData();

	LPCTSTR lpszDisplayName =m_csServiceName;

	 CString message;

	SC_HANDLE  schSCManager;
	SC_HANDLE  schService;

    SERVICE_STATUS ssStatus; 
    DWORD dwOldCheckPoint; 
    DWORD dwStartTickCount;
    DWORD dwWaitTime;
    DWORD dwStatus;

	schSCManager = OpenSCManager( 
    NULL,                    // local machine 
    NULL,                    // ServicesActive database 
    SC_MANAGER_ALL_ACCESS);  // full access rights 
 
   if (schSCManager == NULL) 
   {   //MyErrorExit("OpenSCManager");
	   message="Could not access the services control manager";
	   
	   MessageBox(message," Error",MB_OK);
	   	


	   return;

   }





 
    schService = OpenService( 
        schSCManager,          // SCM database 
        m_csServiceName,          // service name
        SERVICE_ALL_ACCESS); 
 
     if (schService == NULL) 
  {   //MyErrorExit("OpenSCManager");
	   message="Could not access the service ";
	   
	   MessageBox(message," Error",MB_OK);
	    CloseServiceHandle(schSCManager); 

	   return;

   }
 
    if (!StartService(
            schService,  // handle to service 
            0,           // number of arguments 
            NULL) )      // no arguments 
    {
 	   message="Could not start the service ";
	   
	   MessageBox(message," Error",MB_OK);
	   		CloseServiceHandle(schService); 
	    CloseServiceHandle(schSCManager); 

	   return;

    }
    else 
    {
        printf("Service start pending.\n"); 
    }
 
    // Check the status until the service is no longer start pending. 
 
    if (!QueryServiceStatus( 
            schService,   // handle to service 
            &ssStatus) )  // address of status information structure
    {
  	   message="Could not query the service status ";
	   
	   MessageBox(message," Error",MB_OK);
	   		CloseServiceHandle(schService); 
	    CloseServiceHandle(schSCManager); 

	   return;
    }
 
    // Save the tick count and initial checkpoint.

    dwStartTickCount = GetTickCount();
    dwOldCheckPoint = ssStatus.dwCheckPoint;

    while (ssStatus.dwCurrentState == SERVICE_START_PENDING) 
    { 
        // Do not wait longer than the wait hint. A good interval is 
        // one tenth the wait hint, but no less than 1 second and no 
        // more than 10 seconds. 
 
        dwWaitTime = ssStatus.dwWaitHint / 10;

        if( dwWaitTime < 1000 )
            dwWaitTime = 1000;
        else if ( dwWaitTime > 10000 )
            dwWaitTime = 10000;

        Sleep( dwWaitTime );

        // Check the status again. 
 
        if (!QueryServiceStatus( 
                schService,   // handle to service 
                &ssStatus) )  // address of structure
            break; 
 
        if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
        {
            // The service is making progress.

            dwStartTickCount = GetTickCount();
            dwOldCheckPoint = ssStatus.dwCheckPoint;
        }
        else
        {
            if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
            {
                // No progress made within the wait hint
                break;
            }
        }
    } 

    if (ssStatus.dwCurrentState == SERVICE_RUNNING) 
    {
      message="The Service has been started!!";
	   
	   MessageBox(message," Error",MB_OK);
        dwStatus = NO_ERROR;
    }
    else 
    { 
        printf("\nService not started. \n");
        printf("  Current State: %d\n", ssStatus.dwCurrentState); 
        printf("  Exit Code: %d\n", ssStatus.dwWin32ExitCode); 
        printf("  Service Specific Exit Code: %d\n", 
            ssStatus.dwServiceSpecificExitCode); 
        printf("  Check Point: %d\n", ssStatus.dwCheckPoint); 
        printf("  Wait Hint: %d\n", ssStatus.dwWaitHint); 
        dwStatus = GetLastError();
    } 
 
    CloseServiceHandle(schService); 
	CloseServiceHandle(schSCManager); 
	

}

void CControlServiceDlg::OnBnClickedstop()
{
   UpdateData();

	LPCTSTR lpszDisplayName =m_csServiceName;

	 CString message;

	SC_HANDLE  schSCManager;
	SC_HANDLE  schService;


    SERVICE_STATUS ssStatus; 
    DWORD fdwAccess; 
    DWORD dwStartTickCount, dwWaitTime;
	DWORD fdwControl;
 
    // The required service object access depends on the control. 
 
	schSCManager = OpenSCManager( 
    NULL,                    // local machine 
    NULL,                    // ServicesActive database 
    SC_MANAGER_ALL_ACCESS);  // full access rights 
 
   if (schSCManager == NULL) 
   {   //MyErrorExit("OpenSCManager");
	   message="Could not access the services control manager";
	   
	   MessageBox(message," Error",MB_OK);
	   return;

   }

   fdwControl=SERVICE_CONTROL_STOP;

    switch (fdwControl) 
    { 
        case SERVICE_CONTROL_STOP: 
            fdwAccess = SERVICE_STOP; 
            break; 
 
        case SERVICE_CONTROL_PAUSE: 
        case SERVICE_CONTROL_CONTINUE: 
            fdwAccess = SERVICE_PAUSE_CONTINUE; 
            break; 
 
        case SERVICE_CONTROL_INTERROGATE: 
            fdwAccess = SERVICE_INTERROGATE; 
            break; 
 
        default: 
            fdwAccess = SERVICE_INTERROGATE; 
    } 
 
    // Open a handle to the service. 
 
    schService = OpenService( 
        schSCManager,        // SCManager database 
        m_csServiceName,        // name of service 
        fdwAccess);          // specify access 
    if (schService == NULL) 
	{
        message="Could not Open the Service!!";
	    MessageBox(message," Error",MB_OK);

	    CloseServiceHandle(schSCManager); 

		return;
	}
    // Send a control value to the service. 
 
    if (! ControlService( 
            schService,   // handle to service 
            fdwControl,   // control value to send 
            &ssStatus) )  // address of status info 
  	{
        message="Could not Stop the Service!!";
	    MessageBox(message," Error",MB_OK);
		CloseServiceHandle(schService); 
	    CloseServiceHandle(schSCManager); 

		return;
	}
 
    // Print the service status. 
 
    printf("\nStatus of Sample_Srv: \n");
    printf("  Service Type: 0x%x\n", ssStatus.dwServiceType); 
    printf("  Current State: 0x%x\n", ssStatus.dwCurrentState); 
    printf("  Controls Accepted: 0x%x\n", 
        ssStatus.dwControlsAccepted); 
    printf("  Exit Code: %d\n", ssStatus.dwWin32ExitCode); 
    printf("  Service Specific Exit Code: %d\n", 
        ssStatus.dwServiceSpecificExitCode); 
    printf("  Check Point: %d\n", ssStatus.dwCheckPoint); 
    printf("  Wait Hint: %d\n", ssStatus.dwWaitHint); 
 

	CloseServiceHandle(schService); 
	CloseServiceHandle(schSCManager); 


    return; 



}

void CControlServiceDlg::OnBnClickedweave()
{
	 UpdateData();

LPCTSTR lpszDisplayName =m_csServiceName;

	CString message;

	SC_HANDLE  schSCManager;
	SC_HANDLE  schService;


    SERVICE_STATUS ssStatus; 
    DWORD fdwAccess; 
    DWORD dwStartTickCount, dwWaitTime;
	DWORD fdwControl;
 
    // The required service object access depends on the control. 
 
	schSCManager = OpenSCManager( 
    NULL,                    // local machine 
    NULL,                    // ServicesActive database 
    SC_MANAGER_ALL_ACCESS);  // full access rights 
 
   if (schSCManager == NULL) 
   {   //MyErrorExit("OpenSCManager");
	   message="Could not access the services control manager";
	   
	   MessageBox(message," Error",MB_OK);
	   return;

   }

   
   fdwControl=UD_WEAVE_REQUEST;

   fdwAccess=SERVICE_USER_DEFINED_CONTROL;

   
    // Open a handle to the service. 
 
    schService = OpenService( 
        schSCManager,        // SCManager database 
        m_csServiceName,        // name of service 
        fdwAccess);          // specify access 
    if (schService == NULL) 
	{
        message="Could not Open the Service!!";
	    MessageBox(message," Error",MB_OK);

	    CloseServiceHandle(schSCManager); 

		return;
	}
    // Send a control value to the service. 
 
    if (! ControlService( 
            schService,   // handle to service 
            fdwControl,   // control value to send 
            &ssStatus) )  // address of status info 
  	{
        message="Could not weave !!";
	    MessageBox(message," Error",MB_OK);
		CloseServiceHandle(schService); 
	    CloseServiceHandle(schSCManager); 

		return;
	}
 
    // Print the service status. 
 
    printf("\nStatus of Sample_Srv: \n");
    printf("  Service Type: 0x%x\n", ssStatus.dwServiceType); 
    printf("  Current State: 0x%x\n", ssStatus.dwCurrentState); 
    printf("  Controls Accepted: 0x%x\n", 
        ssStatus.dwControlsAccepted); 
    printf("  Exit Code: %d\n", ssStatus.dwWin32ExitCode); 
    printf("  Service Specific Exit Code: %d\n", 
        ssStatus.dwServiceSpecificExitCode); 
    printf("  Check Point: %d\n", ssStatus.dwCheckPoint); 
    printf("  Wait Hint: %d\n", ssStatus.dwWaitHint); 
 

	CloseServiceHandle(schService); 
	CloseServiceHandle(schSCManager); 


    return; 
}

void CControlServiceDlg::OnBnClickedunweave()
{
 UpdateData();

LPCTSTR lpszDisplayName =m_csServiceName;

	CString message;

	SC_HANDLE  schSCManager;
	SC_HANDLE  schService;


    SERVICE_STATUS ssStatus; 
    DWORD fdwAccess; 
    DWORD dwStartTickCount, dwWaitTime;
	DWORD fdwControl;
 
    // The required service object access depends on the control. 
 
	schSCManager = OpenSCManager( 
    NULL,                    // local machine 
    NULL,                    // ServicesActive database 
    SC_MANAGER_ALL_ACCESS);  // full access rights 
 
   if (schSCManager == NULL) 
   {   //MyErrorExit("OpenSCManager");
	   message="Could not access the services control manager";
	   
	   MessageBox(message," Error",MB_OK);
	   return;

   }

   fdwControl=UD_UNWEAVE_REQUEST;

   fdwAccess=SERVICE_USER_DEFINED_CONTROL;

   
    // Open a handle to the service. 
 
    schService = OpenService( 
        schSCManager,        // SCManager database 
        m_csServiceName,        // name of service 
        fdwAccess);          // specify access 
    if (schService == NULL) 
	{
        message="Could not Open the Service!!";
	    MessageBox(message," Error",MB_OK);

	    CloseServiceHandle(schSCManager); 

		return;
	}
    // Send a control value to the service. 
 
    if (! ControlService( 
            schService,   // handle to service 
            fdwControl,   // control value to send 
            &ssStatus) )  // address of status info 
  	{
        message="Could not unweave !!";
	    MessageBox(message," Error",MB_OK);
		CloseServiceHandle(schService); 
	    CloseServiceHandle(schSCManager); 

		return;
	}
 
    // Print the service status. 
 
    printf("\nStatus of Sample_Srv: \n");
    printf("  Service Type: 0x%x\n", ssStatus.dwServiceType); 
    printf("  Current State: 0x%x\n", ssStatus.dwCurrentState); 
    printf("  Controls Accepted: 0x%x\n", 
        ssStatus.dwControlsAccepted); 
    printf("  Exit Code: %d\n", ssStatus.dwWin32ExitCode); 
    printf("  Service Specific Exit Code: %d\n", 
        ssStatus.dwServiceSpecificExitCode); 
    printf("  Check Point: %d\n", ssStatus.dwCheckPoint); 
    printf("  Wait Hint: %d\n", ssStatus.dwWaitHint); 
 

	CloseServiceHandle(schService); 
	CloseServiceHandle(schSCManager); 


    return; 
}
